#!/bin/bash

# This script will build the project and run the tests.
# 定义项目根目录
PROJECT_ROOT=$(realpath "$(dirname "$0")")

# 定义构建目录
BUILD_DIR="$PROJECT_ROOT/build"

# 定义是否启用测试，默认未启动 OFF
ENABLE_TEST=${ENABLE_TEST:-OFF}

# 创建并进入构建目录
mkdir -p "$BUILD_DIR"
cd "$BUILD_DIR" || { echo "无法进入构建目录 $BUILD_DIR，退出..."; exit 1; }

# 运行 cmake 配置
cmake .. -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTS=$ENABLE_TEST
# 检查 CMake 是否成功执行
if [ $? -ne 0 ]; then
    echo "CMake configuration failed. Exiting..."
    exit 1
fi

# 编译项目
make -j$(nproc) VERBOSE=1
# 检查编译是否成功
if [ $? -ne 0 ]; then
    echo "Build failed. Exiting..."
    exit 1
fi
echo "项目构建成功，可执行文件位于 $PROJECT_ROOT/bin 目录下。"

# 检查是否启用测试
if [ "$ENABLE_TEST" = "ON" ]; then
    # 运行测试
    ctest --output-on-failure
fi